package com.party.admin.web.controller.openPlatform;

import com.party.admin.biz.openPlatform.WechatOpenMemberBizService;
import com.party.admin.biz.wechat.WechatBizService;
import com.party.admin.biz.wechat.WechatTokenBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.wechat.GetTicketResponse;
import com.party.common.constant.Constant;
import com.party.common.utils.StringUtils;
import com.party.core.model.member.DeployType;
import com.party.core.model.member.MemberExternalApp;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.member.IMemberExternalAppService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.wechat.IWechatDefaultTemplateService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 微信开放平台控制器
 * Created by wei.li.
 *
 * @date 2018/1/23 0023
 * @time 15:37
 */
@Controller
@RequestMapping(value = "wechat/openMember")
public class WechatOpenMemberController {

    private static Logger logger = LoggerFactory.getLogger(WechatOpenMemberController.class);

    @Autowired
    private WechatOpenMemberBizService wechatOpenMemberBizService;

    @Autowired
    private IWechatDefaultTemplateService wechatDefaultTemplateService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private IMemberExternalAppService memberExternalAppService;

    @Autowired
    private WechatBizService wechatBizService;

    @Autowired
    private WechatTokenBizService wechatTokenBizService;

    @ResponseBody
    @RequestMapping(value = "init")
    public AjaxResult init(){
        wechatOpenMemberBizService.init();
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping(value = "initExternalApp")
    public AjaxResult initExternalApp(){
        wechatOpenMemberBizService.initExternalApp();
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping(value = "initDefaultTemplate")
    public AjaxResult initDefaultTemplate() {
        try {
            logger.info("开始初始化微信模板消息");
            String systemId = wechatOpenMemberService.getSystem().getId();

            List<MemberGroup> partnerList = memberGroupService.getAllPartnerNoOpenStatus();

        /*List<Member> partnerList = Lists.newArrayList();
        Member m = memberService.get("949b34062d7e4ce685421df3889e6319");
        partnerList.add(m);*/

            MemberExternalApp memberExternalApp;

            List<String> eventNames = Arrays.asList("众筹成功推送", "众筹支持消息推送", "收到众筹回复推送");

            for (MemberGroup member: partnerList) {
                memberExternalApp = memberExternalAppService.findByMemberIdAndDeployType(member.getId(), member.getDeployType());
                if (null == memberExternalApp) {
                    continue;
                }
                // 若果机构是配置的平台账号, 就部用添加模板消息了
                if (systemId.equals(memberExternalApp.getExternalAccountId())) {
                    continue;
                }
                boolean authorization = Integer.valueOf(0).equals(member.getDeployType());
                String s = wechatDefaultTemplateService.defaultTemplateMessage(eventNames, member.getId(),authorization);
                logger.info(s);
            }
            logger.info("初始化微信模板消息结束");
        } catch (Exception e) {
            logger.error("初始化微信模板消息异常", e);
        }
        return AjaxResult.success();
    }

    /**
     * @param
     * @return void
     * @Author yifeng
     * @Description 刷新配置方式的公众号token和ticket
     * @Date 10:52 2019/1/14
     **/
    @ResponseBody
    @RequestMapping("refreshWechatOpenMember")
    public void refreshWechatOpenMember() {
        WechatOpenMember wechatOpenMember = new WechatOpenMember();
        wechatOpenMember.setDeployType(DeployType.FILL_IN.getCode());
        List<WechatOpenMember> list = wechatOpenMemberService.list(wechatOpenMember);
        for (WechatOpenMember w : list) {
            try {
                String token;
                if (Constant.WECHAT_ACCOUNT_TYPE_SYSTEM.equals(w.getType())) {
                    token = wechatTokenBizService.getToken();
                } else {
                    boolean refreshToken = wechatBizService.refreshToken(w.getType());
                    if (!refreshToken) {
                        continue;
                    }
                    token = wechatTokenBizService.getToken(w.getAuthorizerAppid(), w.getSecret());
                }
                if (StringUtils.isEmpty(token)) {
                    continue;
                }
                w.setAuthorizerAccessToken(token);
                w.setUpdateDate(new Date());
                wechatOpenMemberService.update(w);

                GetTicketResponse getTicketResponse = wechatBizService.getTicket(w.getAuthorizerAccessToken());
                if (null != getTicketResponse && null != getTicketResponse.getTicket()) {
                    w.setTicket(getTicketResponse.getTicket());
                    w.setUpdateDate(new Date());
                    wechatOpenMemberService.update(w);
                }
            } catch (Exception e) {
                logger.error("刷新公众号信息异常——appId：" + w.getAuthorizerAppid() + "；appName:" + w.getNickName(), e);
                continue;
            }
        }
    }
}
